from .models import User
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
import re


class CreateUserSerializer(serializers.ModelSerializer):
    """注册用户序列化器"""
    # 序列化器的所有字段 id username password password2 name, mobile sms_code, allow
    # 需要校验的字段  username password password2 name mobile sms_code allow
    # 模型中已存在的字段 username password mobile
    # 需要序列化的字段 id, username mobile name
    # write_only————只做反序列化，不做序列化
    # read_only————只做序列化输出，不做反序列化
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'name', 'mobile', 'sms_code', 'allow', 'token']
        # 修改字段属性
        extra_xargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_message': {
                    'min_length': '用户名必须是 5-20个字母',
                    'max_length': '用户名必须是 5-20个字母'
                }
            },
            'password': {
                'write_only': True,  # 只做反序列化，不做序列化
                'min_length': 8,
                'max_length': 20,
                'error_message': {
                    'min_length': '密码必须是 8-20个字符',
                    'max_length': '密码必须是 8-20个字符'
                }
            }
        }

    def validate_mobile(self, value):
        """单独校验手机号"""
        if not re.match(r'1[3-9]\d{9}$' ,value):
            raise serializers.ValidationError('手机号格式错误！')
        return value

    def validate_allow(self, value):
        """是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议!')
        return value

    def validate(self, attrs):
        """校验两次密码是否项目"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码输入不一致！')
        # 校验验证码
        redis_conn = get_redis_connection('verify_code')
        real_sms_code = redis_conn.get('sms_%s' % attrs['mobile'])
        # redis存储的字符串都是以bytes存储，取出来都是bytes类型，需要decode

        if real_sms_code is None or attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误或验证码已过期！')

        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)

        user.save()
        jwt_payload_hander = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handle = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_hander(user)
        token = jwt_encode_handle(payload)

        return user
